﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace STSdb.MTL
{
    public class TableRow<TKey, TValue>
    {
        private TKey _key;
        private TValue _value;

        Transaction _transaction = null;
        string _tableName = String.Empty;

        public bool _existsInDatabase = true;

        public TableRow()
        {           
            _existsInDatabase = false;
        }

       
        public TableRow(TKey key, TValue value,string tableName,Transaction transaction,bool existsInDatabase)
        {
            if(key == null)
                key = default(TKey);

            if (value == null)
                value = default(TValue);

            this._key = key;
            this._value = value;

            this._transaction = transaction;
            this._tableName = tableName;

            this._existsInDatabase = existsInDatabase;
        }

        public TKey Key
        {
            get
            {
                return this._key;
            }
            set
            {
                if (this._transaction == null)
                    throw new Exception("STSdb.MTL: TableRow IS DISCONNECTED FROM THE TRANSACTION");

                _transaction.UpdateKey<TKey, TValue>(this._tableName, this._key, value);

                this._key = value;
            }
        }

        public TValue Value
        {
            get { return this._value; }
            set
            {
                if(this._transaction == null)
                    throw new Exception("STSdb.MTL: TableRow IS DISCONNECTED FROM THE TRANSACTION");

                _transaction.UpdateValue<TKey, TValue>(this._tableName, this._key, value);
                
                this._value = value;
            }
        }

        /// <summary>
        /// If value is a class and we change class property during transaction,
        /// <para>we need to call Update() explicitely to tell the system that class inside the value is changed.</para>
        /// </summary>
        public void Update()
        {
            if (this._transaction == null)
                throw new Exception("STSdb.MTL: TableRow IS DISCONNECTED FROM THE TRANSACTION");

            _transaction.UpdateValue<TKey, TValue>(this._tableName, this._key, this._value);
        }

        /// <summary>
        /// Is Set to true if KeyValue pair is found in the table.
        /// <para>If not - then variables acquire their default(TKey or TValue) intial values</para>
        /// </summary>
        public bool Exists
        {
            get { return this._existsInDatabase; }
        }

    }
}
